package controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.DAO;
import model.EventInfo;
import model.UserProfile;

import org.codehaus.jackson.map.ObjectMapper;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import java.util.logging.Logger;

public class EventUploadServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(EventUploadServlet.class.getName());
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

	private DAO dao = new DAO();
	ObjectMapper mapper = new ObjectMapper();

    public static final String 
 arrayToString (byte[] bytes)
 { 
        StringBuffer buff = new StringBuffer(); 
        for (int i=0; i< bytes.length ; i++) 
        { 
            buff.append(bytes[i] + " "); 
        } 
        return buff.toString(); 
    }
    
	private long createEvent(HttpServletRequest req, BlobKey blobKey)
	{	
		long eid = 0;
		String uid = req.getParameter("uid");
		
		UserProfile up = dao.getUserProfileById(uid);
		String jid = up.getJid(); 
		System.out.println("Create Event by Jid :" + jid);
		
		
		try {
			String min = req.getParameter("deadline");
			Calendar rightNow = Calendar.getInstance();
			rightNow.add(Calendar.MINUTE, Integer.parseInt(min));
			
	        String brief = req.getParameter("brief");
	        //brief = new String(brief.getBytes("8859_1"), "UTF-8");	
	        String name = req.getParameter("name");
	        //name = new String(brief.getBytes("8859_1"), "UTF-8");
	        String place = req.getParameter("place");
	        //place = new String(place.getBytes("8859_1"), "UTF-8");
	        System.out.println(arrayToString(place.getBytes("UTF-8")));

			EventInfo ei = dao.createEventInfo(
					uid,
					Integer.parseInt(req.getParameter("type")),
					name,
					brief,
					rightNow.getTime(),
					Integer.parseInt(req.getParameter("limitCount")),
					Double.parseDouble(req.getParameter("x")),
					Double.parseDouble(req.getParameter("y")),
					Double.parseDouble(req.getParameter("user_x")),
					Double.parseDouble(req.getParameter("user_y")),
					place
					);
			
			if(blobKey!=null)
				ei.setPhoto(blobKey);

			ei.setJid(jid);
			
			dao.ofy().put(ei);
			eid = ei.getEid();
			System.out.println("Create Event OK :" + eid);
			} catch(Exception e) {
				e.printStackTrace();
			}
		return eid;
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {		
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		String bloburl = blobstoreService.createUploadUrl("/event/create");
		resp.setContentType("text/plain");
		resp.getWriter().print(bloburl);
	}
    
    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    	
    	//req.setCharacterEncoding("UTF-8");
    	
        Map<String, BlobKey> blobs = blobstoreService.getUploadedBlobs(req);         
        BlobKey blobKey = blobs.get("eventPhoto");
        
        long eid = createEvent(req, blobKey);
        res.sendRedirect("/event?action=create&eid=" + eid);
        /*
        if (blobKey == null) {
            res.sendRedirect("/");
        } else { 
            res.sendRedirect("/serve?blob-key=" + blobKey.getKeyString());
        }
        */
    }
}